﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using KOPLibrary.PreferenceManagement;
using System.Data.SqlTypes;
using KOPLibrary.UpdateService;
using System.IO;
using KOPLibrary.Forms;
using System.Windows.Forms;
using KOPLibrary.Exceptions;
using System.Reflection;
using System.Drawing;
using System.Threading;
using KOPLibrary.Controls;

namespace KOPLibrary
{
    public static class Util
    {

        public static void GoToSupport()
        {
            Process pro = new Process();
            pro.StartInfo.FileName = "http://kurumsalofispaketi.codeplex.com/workitem/list/basic";
            pro.Start();
        }

        public static string NormalizeFileName(string filename, string DefaultFileNameIfResultEmpty)
        {
            string result = filename;
            char[] badcharacters = new char[] { '/', '\\', ':', '*', '?', '"' };
            foreach (char ch in badcharacters)
            {
                result = result.Replace(ch.ToString(), string.Empty);
            }
            return string.IsNullOrEmpty(result.Trim()) ? DefaultFileNameIfResultEmpty : result.Trim();
        }

        public static void UpdateTemplates(TemplateManagement.TemplateType type)
        {
            try
            {
                string datetime = PreferenceManager.ReadKey("LastTemplateUpdate", type);
                DateTime lastupdate;
                if (!DateTime.TryParse(datetime, out lastupdate))
                {
                    lastupdate = SqlDateTime.MinValue.Value;
                }
                KOPLibrary.UpdateService.KOPSoapClient service = new KOPLibrary.UpdateService.KOPSoapClient();
                KOPLibrary.UpdateService.TemplateType sentType = type == TemplateManagement.TemplateType.Excel ? KOPLibrary.UpdateService.TemplateType.Excel : KOPLibrary.UpdateService.TemplateType.Word;
                TemplateInfo[] list = service.GetTemplateUpdates(sentType, lastupdate);
                FileStream fs;
                if (list != null)
                {
                    string temppath;
                    int maxval = list.Count();
                    ProgressForm pf = new ProgressForm();
                    pf.Initialize(1, maxval, "Güncelleniyor...", true, null);
                    int ctr = 0;
                    foreach (TemplateInfo item in list)
                    {
                        ctr++;
                        pf.Update(string.Format("({0}/{1}) - Şablon : {2}", ctr, maxval, item.FilePath));
                        if (pf.Canceled)
                        {
                            pf.Done();
                            return;
                        }
                        temppath = PreferenceManager.GetDefaulTemplatePath(type) + "\\" + item.FilePath;
                        if (!System.IO.Directory.Exists(Path.GetDirectoryName(temppath))) System.IO.Directory.CreateDirectory(Path.GetDirectoryName(temppath));
                        fs = new FileStream(temppath, FileMode.Create);
                        fs.Write(item.Content, 0, item.Content.Length);
                        fs.Close();
                    }
                    PreferenceManager.SaveKeyToTypeRoot("LastTemplateUpdate", DateTime.Now.ToString(), type);
                    pf.Done();
                    if (MessageBox.Show("Bütün şablonlar başarıyla güncellenmiştir.\nİndirme klasörü açılsın mı?", "Şablon Güncelleme", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        using (Process pro = new Process())
                        {
                            pro.StartInfo.FileName = PreferenceManager.GetDefaulTemplatePath(type);
                            pro.Start();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Son güncellemeden buyana herhangi bir yeni şablon bulunamadı.","Sonuç");
                    return;
                }
            }
            catch (Exception ee)
            {
                ExceptionManager.ShowException(ee);
            }
        }
        public static void CheckUpdateWeekly()
        {
            if (PreferenceManager.ReadKey("CheckUpdates") == "False") return;
            string lastupdatelastcheckdate = PreferenceManager.ReadKey("LastUpdateCheck");
            if (!string.IsNullOrEmpty(lastupdatelastcheckdate))
            {
                if (DateTime.Now.CompareTo(DateTime.Parse(lastupdatelastcheckdate).AddDays(7)) == 1)
                {
                    Thread thrd = new Thread(new ThreadStart(UpdateAddinThread));
                    thrd.Start();
                }
            }
            else
            {
                Thread thrd = new Thread(new ThreadStart(UpdateAddinThread));
                thrd.Start();
            }
        }

        public static void UpdateAddinThread()
        {
            try
            {
                VersionResult vr = CheckAddInVersion();
                if (vr != null)
                {
                    if (Confirm(string.Format("Yeni sürüm bulundu!\nYeni eklenti sürümü\t:{0}.{1} {2}Office eklenti paketinizi güncellemek istiyor musunuz?", vr.Major, vr.Minor, Environment.NewLine)))
                    {
                        Process pro = new Process();
                        pro.StartInfo.FileName = vr.Url;
                        pro.Start();
                    }
                }
                PreferenceManager.SaveKey("LastUpdateCheck", DateTime.Now.ToString());
            }
            catch { ;}
        }

        private static VersionResult CheckAddInVersion()
        {
            int maj = Assembly.GetExecutingAssembly().GetName().Version.Major;
            int min = Assembly.GetExecutingAssembly().GetName().Version.Minor;
            KOPLibrary.UpdateService.KOPSoapClient service = new KOPLibrary.UpdateService.KOPSoapClient();
            VersionResult vr = service.CheckVersion(maj, min);
            return vr;
        }
        public static void UpdateAddin()
        {
            try
            {
                VersionResult vr = CheckAddInVersion();
                if (vr != null)
                {
                    if (Confirm(string.Format("Yeni sürüm bulundu!\nYeni eklenti sürümü\t:{0}.{1} {2}Office eklenti paketinizi güncellemek istiyor musunuz?", vr.Major, vr.Minor, Environment.NewLine)))
                    {
                        Process pro = new Process();
                        pro.StartInfo.FileName = vr.Url;
                        pro.Start();
                    }
                }
                else
                {
                    MessageBox.Show("En güncel sürüme sahipsiniz", "Sürüm Kontrol");
                }
            }
            catch (Exception ee)
            {
                ExceptionManager.ShowException(ee);
            }
        }


        public static void OpenDocumentation()
        {
            string installPath = PreferenceManager.ReadKey("InstallPath");
            Process.Start(Path.Combine(installPath, "Kullanıcı Kılavuzu.docx"));
        }

        public static bool Confirm(string text)
        {
            return MessageBox.Show(text, "Onayla", MessageBoxButtons.YesNoCancel) == DialogResult.Yes;
        }

        public static void ShowMessage(string msg)
        {
            MessageBox.Show(msg, "Mesaj", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public static void ShowError(string msg)
        {
            MessageBox.Show(msg, "Mesaj", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        internal static void ShowException(Exception exc)
        {
            ShowError("Hata:" + exc.Message);
        }

        internal static void GoToOfficialWebPage()
        {
            Process pro = new Process();
            pro.StartInfo.FileName = "http://kurumsalofispaketi.codeplex.com";
            pro.Start();
        }
    }
}
